window.onload = function () {
    const origin = `${window.location.protocol}//${window.location.hostname}`;
    // const origin = 'https://xxdt.dev.ganguomob.com';

    let u = navigator.userAgent;
    let isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; //android or uc
    let isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端

    let id = GetQueryString("id") || '';
    let sid = '';
    const url = `${origin}/api/`;

    if (isNaN(+id)) {
        sid = id;
        id = decryptCBC(id);
    }

    // const token = ''
    const androidToken = window.android ? window.android.getToken() : '';
    const token = isAndroid ? androidToken : isiOS ? window.getToken : '';
    const androidClient = window.android;

    // 是否是新版本
    let appVersion = !!GetQueryString("type");

    window.axios.defaults.headers = {
        'Authorization': `Bearer ${token}`,
    };
    new Vue({
        el: '#vm',
        data: {
            data: '',
            type: null, // 1文章 2视频
            teacher: [],
            learned: null,
            hideTop: false,
            getNum: 0,
            selected: 0,
            bgPlayStatus: false,
            hasToken: false,
            sectionId: '',
            appVersion,
        },
        filters: {
            // 将整数转化成时分秒
            formatTime(second = 0) {
                return formatTime(second)
            }
        },
        watch: {
            getNum(val) {
                if (val === 2) {
                    wxConfig(`${url}supplier/wechat/config?url=${location.href}`,() => {
                        setShare(
                            [
                                'menuItem:share:appMessage',
                                'menuItem:share:timeline',
                                'menuItem:share:qq',
                                'menuItem:share:QZone'
                            ],
                            {
                                link: location.href,
                                imgUrl: `${origin}/admin/h5/img/logo.png`,
                                title: this.data.name,
                                desc: `实战经验分享: ${this.data.name}-${this.teacher[0].name}-${this.teacher[0].position}`,
                            },
                        );
                    });
                }
            },
        },
        methods: {
            fetchData() {
                if (!id) return Toast('请输入id',300);
                axios.get(`${url}supplier/section/${id}`)
                  .then((res)=> {
                    this.getNum++;
                    if(res.data.code > 200) {
                        Toast(res.data.message,300);
                        return;
                    }
                    this.data = res.data.data;
                    document.title = res.data.data.name || '文章学习'
                  }).then(() => {
                        openAPP(this.data.name);

                        const video = document.getElementById('video');
                        if (video) {
                            video.addEventListener('pause', () => {
                                this.sayVideoStatus('0');
                            })
                            video.addEventListener('playing', () => {
                                this.sayVideoStatus('1');
                            })
                        }

                  }).catch((error)=> {
                    Toast(error.data.message,300);
                  });
            },
            getTeacher() {
                if (!id) return Toast('请输入id',300);
                axios.get(`${url}teacher/section/${id}`)
                  .then((res)=> {
                    this.getNum++;
                    if(res.data.code > 200) {
                        Toast(res.data.message,300);
                        return;
                    }
                    this.teacher = res.data.data;
                  }).catch((error)=> {
                    Toast(error.data.message,300);
                  });
            },
            getFinish() {
                if (!token) return;
                if (!id) return Toast('请输入id',300);
                axios.get(`${url}section/status/${id}`)
                  .then((res)=> {
                    if(res.data.code > 200) {
                        Toast(res.data.message,300);
                        return;
                    }
                    this.learned = res.data.data.learned || null;
                  }).catch((error)=> {
                    Toast(error.data.message,300);
                  });
            },
            finish() {
                if (!token) return;
                if (!id) return Toast('请输入id',300);
                axios.put(`${url}section/learn/${id}`)
                  .then((res)=> {
                    if(res.data.code > 200) {
                        Toast(res.data.message,300);
                        return;
                    }
                    if (this.learned && this.learned > 0) {
                        this.learned = null
                        Toast('取消完成',300);
                    } else  {
                        this.learned = 1
                        Toast('完成',300);
                    }
                  }).catch((error)=> {
                    Toast(error.data.message,300);
                  });
            },
            getOpinion() {
                axios.get(`${url}section/opinion/${id}`).then(res => {
                    if(res.data.code > 200) return Toast(res.data.message, 1500);
                    const data = res.data.data;
                    if (data) {
                        this.selected = data.opinion;
                        this.sectionId = data.id;
                    }
                });
            },
            onOpinion(val) {
                if (!token) {
                    document.getElementById('t-button').click();
                    return;
                };

                let method = 'post';
                let urlText = `${url}section/opinion`;
                let data = {
                    opinion: val,
                    section_id: id,
                };

                if (this.sectionId) {
                    method = 'put';
                    urlText = `${url}section/opinion/${this.sectionId}`;
                    data = {
                        opinion: +val === this.selected ? 0 : val,
                    };
                }
                axios[method](urlText, data).then(res => {
                    if(res.data.code > 200) return Toast(res.data.message, 1500);
                    if (method === 'post') this.sectionId = res.data.data;
                    this.selected = +val === this.selected ? 0 : val;
                });
            },
            close() {
                document.getElementById('header').style.height = 0;
            },
            // 设置/获取是否允许后台播放的状态
            setBgPlay() {
                if (token) {
                    window.android.setBackgroundPlayingEnabled(!this.bgPlayStatus);
                    this.getBgPlay();
                }
            },
            getBgPlay() {
                if (token) this.bgPlayStatus = window.android.isOpenBackgroundPlaying();
            },

            /**
             * 汇报视频播放状态 (0 暂停/未播放、1 播放）
             * @params status <String>
             * */
            sayVideoStatus(status) {
                if (token) window.android.playStatus(status);
            }
        },
        created() {
            this.fetchData();
            this.getTeacher();
            this.getFinish();
            if (token) this.getOpinion();
        },
        mounted() {
            // vue.js初始化、挂载后再显示
            document.body.style.display = 'block';

            if (androidToken || token) this.hideTop = true;
            this.hasToken = !!token;
            this.getBgPlay();
        },
    });

    function openAPP(name) {
        if (!token) {
            function parseQueryString() {
                var str = window.location.search.slice(1);
                var arr = str.split('&');
                var obj = {};

                for (var i = 0; i < arr.length; i++) {
                    // 一般参数字符串都经过编码，使用decodeURIComponent()方法将键和值转为原始值
                    var item = arr[i].split('=');
                    var key = decodeURIComponent(item[0]);
                    var value = decodeURIComponent(item[1]);
                    obj[key] = value;
                }

                return obj;
            }

            var query = parseQueryString();

            var iOSUrl = "xxdt://course?id=" + id + "&name=" + name + "&sid=" + sid;//填URL Schemes
            var AndroidUrl = "xxdt://course?id=" + id + "&name=" + name + "&sid=" + sid;//填URL Schemes
            new Link({
                button: document.getElementById('t-button'),// 按钮
                androidLink: AndroidUrl,// 安卓的打开链接
                androidDownloadUrl: "//www.msup.com.cn/lm/default/app",// 安卓的下载链接
                androidYyb: false,// android 是否开启应用宝下载
                iosLink: iOSUrl,// ios 打开链接
                ios9Link: '//oia.msup.com.cn/?id=' + id + "&name=" + name + "&sid=" + sid,// ios 的Universal Link
                iosDownloadUrl: "//apps.apple.com/cn/app/id1509656761", // ios 的下载链接
                iosUniversalLinkEnabled: true, // 是否开启 Universal Link
                iosYyb: false,// ios 是否开启应用宝下载
                // yybDownloadUrl: "http://a.app.qq.com/o/simple.jsp?pkgname=com.luojilab.player&ckey=CK1369314671247",// 应用宝下载链接
                autoLaunchApp: false, // 是否打开页面就唤起APP
                autoRedirectToDownloadUrl: true,// 是否自动跳转到下载页面
            })

            new Link({
                button: document.getElementById('download'),// 按钮
                androidLink: AndroidUrl,// 安卓的打开链接
                androidDownloadUrl: "//www.msup.com.cn/lm/default/app",// 安卓的下载链接
                androidYyb: false,// android 是否开启应用宝下载
                iosLink: iOSUrl,// ios 打开链接
                ios9Link: '//oia.msup.com.cn/?id=' + id + "&name=" + name + "&sid=" + sid,// ios 的Universal Link
                iosDownloadUrl: "//apps.apple.com/cn/app/id1509656761", // ios 的下载链接
                iosUniversalLinkEnabled: true, // 是否开启 Universal Link
                iosYyb: false,// ios 是否开启应用宝下载
                // yybDownloadUrl: "http://a.app.qq.com/o/simple.jsp?pkgname=com.luojilab.player&ckey=CK1369314671247",// 应用宝下载链接
                autoLaunchApp: false, // 是否打开页面就唤起APP
                autoRedirectToDownloadUrl: true,// 是否自动跳转到下载页面
            })
        }
    }

    function decryptCBC(msg) {
        const key = CryptoJS.enc.Utf8.parse('a4e0b5bha5za9a51');
        const iv = CryptoJS.enc.Utf8.parse('141dfb09efc61e2b');
        const decrypt = CryptoJS.AES.decrypt(msg, key, {
            iv,
            mode: CryptoJS.mode.CBC,
        });
        return decrypt.toString(CryptoJS.enc.Utf8);
    }
}
